package com.codingman.springbootdemo2;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class AnotherHttpMessageConverter extends AbstractHttpMessageConverter<String> {

	public AnotherHttpMessageConverter() {
		super(new MediaType("text", "another"));
	}
	
	@Override
	protected boolean supports(Class<?> clazz) {
		return String.class == clazz;
	}

	@Override
	protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		String requestBody = StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8);
		
		ObjectMapper mapper = new ObjectMapper();
		JsonNode node = mapper.readTree(requestBody);
		String body = node.get("body").asText();
		String signature = node.get("signature").asText();
		
		String base64 = Base64.getEncoder().encodeToString(body.getBytes("utf-8"));
		if(base64.equals(signature))
			return body;
		else
			return "";
	}

	@Override
	protected void writeInternal(String str, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		String base64 = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
		
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode node = mapper.createObjectNode();
		node.put("body", str);
		node.put("signature", base64);
		
		StreamUtils.copy(node.toString(), StandardCharsets.UTF_8, outputMessage.getBody());
	}

}
